package com.my.swas.sso.common.base;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.my.swas.common.jwt.JWTToken;
import com.my.swas.common.jwt.JWTUtils;
import com.my.swas.common.utils.CacheUtils;
import com.my.swas.common.utils.RedisUtil;
import com.my.swas.common.constans.CommConst;
import com.my.swas.sso.common.constans.CacheConst;
import com.my.swas.sso.module.admin.entity.User;
import com.my.swas.sso.module.admin.service.MenuService;
import com.my.swas.sso.module.admin.vo.ResTreeSelectVo;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Description:
 * @author: :MaYong
 */
@Component
public class BaseController {
    @Resource
    public CacheUtils cacheUtils;
    @Resource
    public RedisUtil redisUtil;
    @Resource
    private MenuService resourcesService;

    /**
     * 获取用户名称
     */
    public  String getUserAccount(){
        return JWTUtils.getUserAccount();
    }

    /**
     * 获取用户ID
     */
    public Long getUserId(){
        return JWTUtils.getUserId();
    }

    public void setUser(User user){
        if(null == user){return;}
        cacheUtils.setStr(CacheConst.EH_SSO_USER+user.getId(), JSONObject.toJSONString(user));
    }

    public User getUser(){
        String userString  = cacheUtils.getStr(CacheConst.EH_SSO_USER+getUserId());
        if(StrUtil.isNotBlank(userString)){
            return JSONObject.parseObject(userString,User.class);
        }else{
            return null;
        }
    }

    /**
     * 刷新菜单
     */
    public List<ResTreeSelectVo> refreshMainTree(){
        List<ResTreeSelectVo>  resTreeSelectVoList = resourcesService.treeSelectList(1l, CommConst.ONE,null);
        cacheUtils.setStr(CacheConst.EH_MAIN_TREE + getUserId(),JSONObject.toJSONString(resTreeSelectVoList));
        if(CollectionUtil.isEmpty(resTreeSelectVoList)){
            resTreeSelectVoList = Lists.newArrayList();
        }
        return resTreeSelectVoList;
    }

    /**
     * 刷新菜单
     */
    public List<ResTreeSelectVo> refreshMainTree(JWTToken jwtToken){
        List<ResTreeSelectVo>  resTreeSelectVoList = resourcesService.treeSelectList(1l, CommConst.ONE,jwtToken);
        cacheUtils.setStr(CacheConst.EH_MAIN_TREE + JWTUtils.getUserId(jwtToken.getPrincipal().toString()),JSONObject.toJSONString(resTreeSelectVoList));
        if(CollectionUtil.isEmpty(resTreeSelectVoList)){
            resTreeSelectVoList = Lists.newArrayList();
        }
        return resTreeSelectVoList;
    }


}
